<?php

abstract class ProjectFormAction extends CAction {
	
	protected $owner;
	protected $project;
	protected $specificData;
	protected $cities;

	public function run() {
		$this->controller->layout = 'empty';
		$this->controller->pageTitle = 'New project';
		
		$this->owner = $this->getOwner();
		$this->project = $this->getProject();
		
		$update = $this->saveProject();
		
		$this->specificData = array();
		if ($this->owner->specific_data != null) {
			foreach ($this->owner->specific_data as $specific_data) {
				$this->specificData[$specific_data->field_name] = $specific_data;
			}
		}
		
		$param = Yii::app()->parameter->getParametersArray('OWNER_SPEC');
		foreach ($param as $id=>$specificDatum) {
			$id = $param[$id]['FLDNAM'];
			if (!array_key_exists($id, $this->specificData)) {
				$this->specificData[$id] = new OwnerSpecificData();
				$this->specificData[$id]->field_name = $id;
			}
		}
		
		if ($update) {
			$this->controller->redirect(array('steps','id'=>$this->project->id));
		} else {
			$this->controller->render('project', array (
				'owner' => $this->owner,
				'project' => $this->project,
				'specificData' => $this->specificData,
				'cities' => $this->cities
			));
		}
	}
	
	private function saveProject() {
		$update = false;
		$saved = false;
		
		if (isset($_POST['Owner'])) {
			if ($_POST['Owner']['id'] != "") {
				$this->owner = Owner::model()->findByPk($_POST['Owner']['id']);
				if ($this->owner == null) {
					$this->owner = new Owner();
					$this->owner->adviser_initials = Yii::app()->user->getState('dbuser')->initials;
				} else {
					$this->owner->setIsNewRecord(false);
				}
			}
			unset($_POST['Owner']['id']);
			
			$this->owner->attributes = $_POST['Owner'];
			$this->owner->birth_date = DateUtils::parse(Constants::YII_DISPLAY_DATE_FORMAT, $this->owner->birth_date);
			
			if (trim($_POST['city_name']) == "") {
				$this->owner->city_id == "";
			}
			
			if(($this->owner->city_id == null || $this->owner->city_id == "") && trim($_POST['city_name']) != "") {
				// on a une recherche de ville en cours.
				$this->cities = $this->controller->findCities(trim($_POST['city_name']), 20);
				
				if ($this->cities != null && count($this->cities) == 1) {
					// on trouve un seul résultat : OK
					$this->owner->city_id = $this->cities[0]->id;
					$_POST['city_name'] = $this->cities[0]->label;
					$this->cities = null;
				} 
			} else {
				$_POST['city_name'] = City::model()->findByPk($this->owner->city_id)->label;
			}
			
			$update = true;
		}
		
		if (isset($_POST['OwnerSpecificData'])) {
			$s = array();
			foreach ($_POST['OwnerSpecificData'] as $id => $specific_datum) {
				$tmp = new OwnerSpecificData();
				$tmp->attributes = $specific_datum;
				$s[] = $tmp;
			}
			$this->owner->specific_data = $s;
			$update = true;
		}
		
		if (isset($_POST['Project'])) {
			if ($_POST['Project']['id'] != "") {
				$this->project = Project::model()->findByPk($_POST['Project']['id']);
				if ($this->project == null) {
					$this->project = new Owner();
				} else {
					$this->project->setIsNewRecord(false);
				}
			} 
			unset($_POST['Project']['id']);
			
			$this->project->attributes = $_POST['Project'];
			$update = true;
		}
		
		if ($update) {
			$transaction = Yii::app()->db->beginTransaction();
			$update = false;
			$force_update = true;
			if ($this->owner->validate() & $this->project->validate()) {
				// Save owner data
				if ($this->owner->save()) {
					foreach ($_POST['OwnerSpecificData'] as $name => $specific_data) {
						$specific_data = OwnerSpecificData::model()->findByPk(array('owner_id' => $this->owner->id, 'field_name' =>$name));
						if ($specific_data == null) {
							$specific_data = new OwnerSpecificData();
							$specific_data->owner_id = $this->owner->id;
							$specific_data->field_name = $name;
						} else {
							$specific_data->setIsNewRecord(false);
						}
						$specific_data->attributes = $_POST['OwnerSpecificData'][$name];
						if (!$specific_data->validate() && !$specific_data->save()){
							$force_update = false;
						}
					}
					
					$this->project->owner_id = $this->owner->id;
					if ($this->project->validate()) {
						if ($this->project->save()) {
							$update = true;
						}
					}
				}
			}
			
			if ($update && $force_update) {
				$transaction->commit();
				$saved = true;
			} else {
				// on ne met pas à jour. on remplace le message d'erreur sur la ville si besoin
				if ($this->owner->city_id == null || $this->owner->city_id == '') {
					if (trim($_POST['city_name']) != "") {
						$this->owner->clearErrors('city_id');
						if ($this->cities == null) {
							$this->owner->addError('city_id', 'Pas de ville trouvée commençant par '.$_POST['city_name']);
						} else {
							$this->owner->addError('city_id', 'Plusieurs villes ont été trouvées. Choisissez dans la liste (20 premières).');
						}
					}
				}
				
				$transaction->rollback();
			}
		}
		
		return $saved;
	}
	
	public abstract function getProject();
	public abstract function getOwner();
}
